package com.aaa.eat.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * Author:张海金
 * Description:T0D0
 * DateTime:2022/3/16 10:58
 **/
@Data
public class OSSUtil {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String path;

    public String uploadOSS(MultipartFile headImg){
       try {
           //随机生成一个乱码  +  获取上传图片类型 例如 123/jpg,然后字符串替换 得到 .jpg。和前面的随机数拼接，得到一个随机的图片名
           String fileName = UUID.randomUUID().toString()+headImg.getContentType().replace("image/",".");

           //创建OSSClient实例
           OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
           InputStream inputStream = headImg.getInputStream();
           ossClient.putObject(bucketName,fileName,inputStream);
           ossClient.shutdown();
           //return 上传在OSS图片的网络路径
           return path+fileName;
       }catch (Exception e){
           e.printStackTrace();
       }
       return null;
    }

}
